// 模拟微信小程序环境的全局对象
// 微信小程序片区总览页面
Page({
  data: {
    areaImage: '',
    jkUrl:'',
    // jkUrl:'http://172.16.130.18:8080',
    // jkUrl:'https://wxapi.kunszbq.cn',
    areaInfo: {
      enterpriseName: '',
    },
   
    dataList: [],
    contractDetailsList: [], // 存储合同详情数据
    scale: 1,
    offsetX: 0,
    offsetY: 0,
    showPopup: false,
    selectedBuilding: {},
    loadingContractDetails: false
  },

  onLoad(options) {
      const app = getApp();
      this.setData({
      jkUrl:app.globalData.jkUrl
    });
    // 从options中获取片区ID等参数
    const enterpriseName= options.name || '';
    this.setData({
      areaInfo: {
        enterpriseName: enterpriseName,
      }
    });
    // 通过接口获取片区统计数据
    this.getDistrictStatistics(enterpriseName);
  },
  
  // 获取片区统计数据
  getDistrictStatistics(enterpriseName) {
    wx.showLoading({ title: '加载中' });

    wx.request({
    
      url: this.data.jkUrl+'/park/contract/list', // 替换为实际的API地址
      method: 'GET',
      data: {
        enterpriseName: enterpriseName
      },
      success: (res) => {
        if (res.data && res.data.code === 200) {
        
          const dataList = res.data.rows || [];
          this.setData({
            dataList: dataList
          });
          
          // 循环dataList，调用/park/contract接口获取合同详情
          this.getAllContractDetails(dataList);
        } else {
          console.error('获取片区数据失败:', res.data);
          wx.showToast({ title: '获取数据失败', icon: 'none' });
          // 如果接口调用失败，使用默认数据
          // this.setDefaultData();
        }
      },
      fail: (err) => {
        console.error('网络请求失败:', err);
        wx.showToast({ title: '网络请求失败', icon: 'none' });
        // 如果网络请求失败，使用默认数据
        // this.setDefaultData();
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  
  // 获取所有合同的详情
  getAllContractDetails(dataList) {
    if (!dataList || dataList.length === 0) {
      return;
    }
    
    this.setData({ loadingContractDetails: true });
    
    // 创建所有合同详情请求的Promise数组
    const promises = dataList.map(item => {
      return new Promise((resolve) => {
        this.getContractDetails(item.id || item.contractId).then(details => {
          resolve({ contractId: item.id || item.contractId, details });
        }).catch(err => {
          console.error(`获取合同ID:${item.id || item.contractId}详情失败:`, err);
          resolve({ contractId: item.id || item.contractId, details: null });
        });
      });
    });
    
    // 等待所有请求完成
    Promise.all(promises).then(results => {
      const contractDetailsList = results.reduce((acc, item) => {
        if (item.details) {
          acc.push({ contractId: item.contractId, ...item.details });
        }
        return acc;
      }, []);
      console.log('===contractDetailsList:', contractDetailsList);
      
      this.setData({
        contractDetailsList,
        loadingContractDetails: false
      });
    }).catch(err => {
      console.error('获取合同详情失败:', err);
      this.setData({ loadingContractDetails: false });
    });
  },
  
  // 获取单个合同的详情
  getContractDetails(contractId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.data.jkUrl + '/park/contract/' + contractId,
        method: 'GET',
        data: {
          id: contractId
        },
        success: (res) => {
          if (res.data && res.data.code === 200) {
            // 假设接口返回的数据中有parkContractDetails数组
            resolve(res.data.data || {});
          } else {
            reject(new Error(`获取合同详情失败，错误码: ${res.data?.code || '未知'}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },
  
  // 设置默认数据
  // setDefaultData() {
  //   this.setData({
  //     areaImage: 'https://via.placeholder.com/1000x800?text=片区总览图',
  //     areaInfo: {
  //       name: '科技创新园区',
  //       location: '科技园南区',
  //       address: '北京市海淀区中关村南大街5号',
  //       totalBuildings: 3,
  //       totalArea: 25000,
  //       leasedArea: 16500,
  //       idleArea: 8500
  //     },
  //     buildings: [
  //       { id: 1, name: 'A1栋', left: '30%', top: '40%', description: '这是一栋现代化厂房', totalArea: 5000, availableArea: 2000, companies: [{ id: 1, name: 'ABC公司' }] },
  //       { id: 2, name: 'A2栋', left: '60%', top: '30%', description: '高标准写字楼', totalArea: 8000, availableArea: 1500, companies: [{ id: 2, name: 'XYZ公司' }, { id: 3, name: 'DEF公司' }] },
  //       { id: 3, name: 'A3栋', left: '40%', top: '70%', description: '多功能综合楼', totalArea: 12000, availableArea: 5000, companies: [] }
  //     ]
  //   });
  // },

  zoomIn() {
    let { scale } = this.data;
    scale = Math.min(scale + 0.2, 3);
    this.setData({
      scale: scale,
      imageStyle: 'scale(' + scale + ') translate(' + this.data.offsetX + 'px, ' + this.data.offsetY + 'px)'
    });
  },

  zoomOut() {
    let { scale } = this.data;
    scale = Math.max(scale - 0.2, 0.5);
    this.setData({
      scale: scale,
      imageStyle: 'scale(' + scale + ') translate(' + this.data.offsetX + 'px, ' + this.data.offsetY + 'px)'
    });
  },

  moveLeft() {
    const offsetX = this.data.offsetX + 50;
    this.setData({
      offsetX: offsetX,
      imageStyle: 'scale(' + this.data.scale + ') translate(' + offsetX + 'px, ' + this.data.offsetY + 'px)'
    });
  },

  moveRight() {
    const offsetX = this.data.offsetX - 50;
    this.setData({
      offsetX: offsetX,
      imageStyle: 'scale(' + this.data.scale + ') translate(' + offsetX + 'px, ' + this.data.offsetY + 'px)'
    });
  },

  moveUp() {
    const offsetY = this.data.offsetY + 50;
    this.setData({
      offsetY: offsetY,
      imageStyle: 'scale(' + this.data.scale + ') translate(' + this.data.offsetX + 'px, ' + offsetY + 'px)'
    });
  },

  moveDown() {
    const offsetY = this.data.offsetY - 50;
    this.setData({
      offsetY: offsetY,
      imageStyle: 'scale(' + this.data.scale + ') translate(' + this.data.offsetX + 'px, ' + offsetY + 'px)'
    });
  },

  onBuildingTap(e) {
    const buildingId = e.currentTarget.dataset.id;
    // 查找选中的楼宇
    const selectedBuilding = this.data.buildings.find(building => building.id == buildingId);
    if (selectedBuilding) {
      this.setData({
        selectedBuilding: selectedBuilding,
        showPopup: true
      });
    }
  },

  closePopup() {
    this.setData({
      showPopup: false
    });
  },

  enterBuildingDetail() {
    const { selectedBuilding } = this.data;
    // 关闭弹窗
    this.closePopup();
    // 跳转到楼宇详情页面
    wx.navigateTo({
      url: '/pages/buildingDetail/buildingDetail?id=' + selectedBuilding.id
    });
  }
});